/// <reference path="../js/jquery.js" />
///列表明细封装
var scroll_container = {};
$.fn.gridList = function () {
    this.gridId = this.attr("id");
    if ($(this).parents(".layermmain").length > 0) {
        this.searchPlane = this.attr("searchPlane") != undefined && this.attr("searchPlane") !=""? $(this).parents(".layermmain").find("#" + this.attr("searchPlane")) : null;
    } else {
        this.searchPlane = this.attr("searchPlane") != undefined && this.attr("searchPlane") != "" ? $("#" + this.attr("searchPlane")) : null;
    }
    var $this = $(this);
    $(this).find(".ckeckAll").click(function () {
        if ($(this).find("a").hasClass("checked")) {
            $(this).find("a").removeClass("checked");
        } else {
            $(this).find("a").addClass("checked");
        }
        if ($(this).find("a").hasClass("checked")) {
            $this.find(".ckeckItem a").addClass("checked");
        } else {
            $this.find(".ckeckItem a").removeClass("checked");
        }
    });
    $(this).on("click", ".ckeckItem", function () {
        if ($(this).find("a").hasClass("checked")) {
            $(this).find("a").removeClass("checked");
        } else {
            $(this).find("a").addClass("checked");
        }
    });
    this.extendSearchWhere = null;
    this.gridData = null;
    this.grid = $(this);
    this.AfterLoadingData = null;
    if (this[0].gridlist == undefined || this[0].gridlist == null)
        this[0].gridlist = this;
    ///通过API查询 加载数据入口
    this.InitPage = function (p, grid) {
        var gridobj = grid || this;
        var introws = $(gridobj.grid).find(".pagination").attr("data-rows") || $(gridobj.grid).find('table').attr("rows");
        var param = {
            rows: introws || 10,
            page: p || 1,
            sidx: gridobj.grid.find('table').attr("data-sidx") != undefined ? gridobj.grid.find('table').attr("data-sidx") : gridobj.grid.attr("data-sidx"),
            sord: gridobj.grid.find('table').attr("data-sord") != undefined ? gridobj.grid.find('table').attr("data-sord") : gridobj.grid.attr("data-sord"),
        };
        if (typeof (this.extendSearchWhere) == "function") {
            this.extendSearchWhere();
        }
        if (gridobj.whereobj != undefined) {
            for (var key in gridobj.whereobj) {
                param[key] = gridobj.whereobj[key];
            }
        }
        gridobj.searchWhere(param);
        var ajaxFunction = AJAXAPI;
        if (gridobj.grid.attr("AjaxType") != undefined && gridobj.grid.attr("AjaxType").toLowerCase() == "web") {
            ajaxFunction = AJAX;

        }
        ajaxFunction(gridobj.grid.attr("sourceApi"), param, function (d) {
            if(d.success) {
                if (gridobj.grid.find("[type*=x-jquery-tmpl]").length > 0) {
                    gridobj.Templ = gridobj.grid.find("[type*=x-jquery-tmpl]");
                }
                if (typeof (d.records) == "undefined") {
                    d.records = d.totalcount;
                    d.page = param.page;
                    d.total = parseInt ( d.totalcount / param.rows + ( d.totalcount % param.rows != 0 ? 1 : 0));
                    d.rows=d.rows==undefined||d.rows==null?d.data:d.rows;
                }
                gridobj.grid.foottable(gridobj.Templ.tmpl(d), param.page, d.records, d.total, gridobj.InitPage, gridobj,param.rows);
                if (($(gridobj.grid).find("#pagenum").val() == "" || $(gridobj.grid).find("#pagenum").val() == null) && $(gridobj.grid).find("#pagenum").length > 0) {
                    $(gridobj.grid).find("#pagenum").val("10");
                }
                gridobj.gridData = d.rows;
                if (typeof (LoadPower) == "function") {
                    LoadPower();
                }
                if (gridobj.IsScroll != true)
                    gridobj.scroll();
                if (typeof (gridobj.AfterLoadingData) == "function")
                    gridobj.AfterLoadingData();
            }else{
                ShowError(d.msg);
            }
        });
    }
    ///加载数据 json数据入口
    this.LoadData = function () {
        var d = {
            page: 1,
            total: 1,
            records: this.gridData.length,
            rows: this.gridData
        };
        this.grid.foottable(this.grid.find("[type*=x-jquery-tmpl]").tmpl(d), d.page, d.records, d.total, null,param.pageszie);
        if (typeof (this.AfterLoadingData) == "function")
            this.AfterLoadingData();
    }
    ///往上查找次数
    var findsearchNum = 0;
    ///拼接查询条件 
    this.searchWhere = function (param) {
        if (this.searchPlane == null || this.searchPlane == undefined) {
            findsearchNum = 0;
            this.searchPlane = this.findsearchPlane(this.grid)
        }
        if (this.searchPlane == null || this.searchPlane == undefined) {
            /// ShowError(window.LangMsg['msg_wmp_not_find_search_panel']);
            return false;
        }
        $(this.searchPlane).find("input").each(function (i, j) {
            if ($(this).val() != "" && $(this).val() != undefined && $(this).attr("id") != undefined) {
                if ($(this).attr("id").length > 3) {
                    switch ($(this).attr("type")) {
                        case "text":
                        case "areatext":
                        case "hidden": param[$(this).attr("id").substring(3, $(this).attr("id").length)] = $(this).val(); break;
                        default: break;
                    }
                }
            }
        });
        $(this.searchPlane).find("select").each(function (i, j) {
            var strval= $(this).WmpSelectBox("getvalue");
            if (strval != "" && strval != undefined && $(this).attr("id") != undefined) {
                if ($(this).attr("id").length > 3) {
                    param[$(this).attr("id").substring(3, $(this).attr("id").length)] = strval;
                }
            }
        });
        $(this.searchPlane).find("div[type]").each(function (i, j) {
            if ($(this).attr("id") != undefined) {
                if ($(this).attr("id").length > 3) {
                    var filedvalue = "";
                    switch ($(this).attr("type")) {
                        case "multuser":
                        case "user":
                        case "dept": filedvalue = ""; var selectorList = $(this).WmpSelect("get");
                            for (var idex = 0; idex < selectorList.length; idex++) {
                                filedvalue = filedvalue == "" ? selectorList[idex].no : filedvalue + ";" + selectorList[idex].no;
                            }
                            break; 

                        case "cost":
                        case "project":
                            filedvalue = encodeURIComponent(JSON.stringify($("#" + $(this).attr("id")).WmpSelect("get")));
                            break;
                        case "checkboxlist":
                            $("#" + $(this).attr("id")).find(".checked").each(function (idex) {
                                filedvalue = (filedvalue == "" ? $(this).attr("value") : filedvalue + ";" + $(this).attr("value"));
                            });
                            break;
                        case "radioList":
                            filedvalue = $("#" + $(this).attr("id")).find(".checked").length > 0 ? $("#" + $(this).attr("id")).find(".checked").attr("value") : "";
                            break;
                    }
                    param[$(this).attr("id").substring(3, $(this).attr("id").length)] = filedvalue;
                }
            }
        });
        return true;
    }
    ///往上级查找 直到查找到有查询按钮的对象
    this.findsearchPlane = function (obj) {
        if ($(obj).parent().find("[onclick*=InitPage]").length > 0) {
            return $(obj).parent()[0];
        }
        findsearchNum++;
        if (findsearchNum < 5)
            return this.findsearchPlane($(obj).parent());
        else
            return null;
    }
    this.collapseToggle = function () {
        $(".collapseToggle").foottableCollapse($(this));
    }
    this.DelRow = function (rowindex) {
        this.gridData.remove(rowIdex);
        this.LoadData();
    }
    this.AddRow = function (item) {
        if (item != null && item != undefined)
            item = {};
        if (this.gridData == null) this.gridData = [];
        this.gridData.push(item);
        this.LoadData();
    }
    ///为弹出层 绑定数据
    this.bindDetailsData = function (dialog, idex) {
        if (idex == undefined || idex == null) return;
        if (this.gridData[idex] == undefined || this.gridData[idex] == null) return;
        var dataItem = this.gridData[idex];
        for (var key in dataItem) {
            var contorl = dialog.find("[id*=" + key + "]");
            if (contorl.length > 0) {
                switch (contorl.attr("type")) {
                    case "hidden": contorl.val(dataItem[key]); break;
                    case "areatext": contorl.val(dataItem[key]); break;
                    case "text": contorl.val(dataItem[key]); break;
                    case "select": contorl.val(dataItem[key]); break;
                    case "radioList": contorl.find("[type=radio]").removeAttr("checked");
                        contorl.find("[value=" + dataItem[key] + "]").click();
                        break;
                    case "checkboxlist": contorl.find("[type=checkbox]").removeAttr("checked");
                        var checkboxValues = dataItem[key].split(";");
                        for (var idex = 0; idex < checkboxValues.length; idex++) {
                            if (checkboxValues[idex] != "")
                                contorl.find("[value=" + checkboxValues[idex] + "]").attr("checked", "checked");
                        }
                        break;
                    default: break;
                }

            }

        }
    }
    this.scroll = function () {
        var gridobj = this;
        gridobj.IsScroll = true;
        if (typeof (window[$(gridobj).attr("newID")]) == "undefined") {
            setTimeout(function () {
                var width = 0;
                //alert(gridobj.gridId);
                gridobj.grid.find("table").find("th").each(function () {
                    width += $(this).outerWidth(true);
                });
                // alert(width);
                if (window.parent.window_width && window.parent.window_width < 769) {
                    gridobj.grid.css("width", window.parent.window_width + "px");
                }
                gridobj.grid.find(".scroll_scroller").css("width", width + "px");
                if (scroll_container == undefined || scroll_container == null) {
                    scroll_container = {};
                }
                if (scroll_container[$(gridobj).attr("newID")]) {
                    scroll_container[$(gridobj).attr("newID")].refresh();
                } else {
                    var scrollID = gridobj.grid.find(".scroll_wrapper").attr("id");
                    if (scrollID == undefined) {
                        scrollID = "scroll" + NewID();
                        $(gridobj).attr("newID", scrollID);
                        gridobj.grid.find(".scroll_wrapper").attr("id", scrollID);
                    }
                    scroll_container[gridobj.grid] = new IScroll("#" + scrollID, {
                        preventDefault: false,
                        scrollbars: true,
                        interactiveScrollbars: true,
                        scrollX: true,
                        scrollY: false,
                        click: true,
                        mouseWheel: false
                    });
                }
            }, 100);
        }

    }
    function NewID() {
         return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
    }
    this.ExportData = function () {
        var gridobj =  this;
        var introws = $(gridobj.grid).find(".pagination").attr("data-rows") || $(gridobj.grid).find('table').attr("rows");
        var param = {
            rows: 100000000,
            page: 1,
            sidx: gridobj.grid.find('table').attr("data-sidx") != undefined ? gridobj.grid.find('table').attr("data-sidx") : gridobj.grid.attr("data-sidx"),
            sord: gridobj.grid.find('table').attr("data-sord") != undefined ? gridobj.grid.find('table').attr("data-sord") : gridobj.grid.attr("data-sord"),
        };
        if (typeof (this.extendSearchWhere) == "function") {
            this.extendSearchWhere();
        }
        if (gridobj.whereobj != undefined) {
            for (var key in gridobj.whereobj) {
                param[key] = gridobj.whereobj[key];
            }
        }
        gridobj.searchWhere(param);
        var datajson=JSON.parse(decodeURIComponent(gridobj.attr("datajson")));
      var urlarry=  gridobj.grid.attr("sourceApi").split("/");
        var xhr = new XMLHttpRequest();
        xhr.open('post', "/comm/ExportExlce/"+urlarry[urlarry.length-1], true);
        xhr.responseType = 'blob';
        xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        xhr.onload = function () {
            if (this.status == 200) {
                var blob = this.response;
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(blob);
                a.href = url;
                //设置文件名称
                a.download = datajson.ModuleTitle+'.xls';
                a.click();
            }
        }
        xhr.send(JSON.stringify(param));
    }
    return this[0].gridlist;
}







